package utils.code;

import java.security.MessageDigest;

/**
 * @program: SpringBootDemos
 * @description: 不可逆加密算法
 * @author: Kangsen
 * @create: 2022-05-20 11:22
 **/
public class MD5 {
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public MD5() {}

    /**
     *
     * MD5不可逆加密函数
     *
     * @param s 待加密字符串,
     * @return String 加密后字符串，如果待加密字符串为null，则返回null
     */
    public final static String getMD5String(String s) {
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取md5摘要结果.
     *
     * @param origin
     *            String
     * @return String
     */
    public static String encrypt(String origin) {
        String resultString = null;

        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes("UTF-8")));
        } catch (Exception ex) {
        }
        return resultString;
    }
    /**
     * 判断数据源与加密数据是否一致，通过验证原数组和生成是hash数组是否为同一数组，验证二者是否为同一数据
     * @param srcStr
     * @param md5HexString
     * @return
     */
    public static boolean vertify(String srcStr,String md5HexString){
        boolean flag = false;
        try {
            if(encrypt(srcStr).equals(md5HexString)) {
                flag = true;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * 转换字节数组为16进制字串
     *
     * @param b
     *            字节数组
     * @return 16进制字串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}
